package com.xy.Servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xy.dao.impl.PageResults;
import com.xy.model.Admin;
import com.xy.model.Cell;
import com.xy.model.StockReceive;
import com.xy.model.StockSelect;
import com.xy.model.Supplier;
import com.xy.model.TextBook;
import com.xy.service.SupplierService;
import com.xy.service.impl.CellServiceImpl;
import com.xy.service.impl.StockReceiveServiceImpl;
import com.xy.service.impl.StockServiceImpl;
import com.xy.service.impl.SupplierServiceImpl;
import com.xy.service.impl.TextBookServiceImpl;

/**
 * Servlet implementation class ReceiveServlet
 */
@WebServlet("/receiveServlet")
public class ReceiveServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ReceiveServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		StockReceiveServiceImpl receiveServiceImpl = new StockReceiveServiceImpl();

		if ("go".equals(request.getParameter("condition"))) {
			SupplierService service = new SupplierServiceImpl();
			List<Supplier> list = service.list(Supplier.class);
			request.getSession().setAttribute("suppliers", list);
			request.getRequestDispatcher("/pages/storage/storage002/receive.jsp").forward(request, response);
		} else if ("detail".equals(request.getParameter("condition"))) {
			int id = Integer.valueOf(request.getParameter("id"));
			TextBook tb = new TextBookServiceImpl().get(id);
			request.setAttribute("tb", tb);
			request.getRequestDispatcher("/pages/storage/storage002/book_detail.jsp").forward(request, response);

		} else if ("getTextBook".equals(request.getParameter("condition"))) {
			String isbn = request.getParameter("isbn");
			List<TextBook> textBooks = new TextBookServiceImpl().getByObject("isbn", isbn);
			request.setAttribute("textBooks", textBooks);
			request.getRequestDispatcher("/pages/storage/storage002/receive.jsp").forward(request, response);

		} else if ("receiveTextBook".equals(request.getParameter("condition"))) {
			StockReceive stockReceive = new StockReceive();
			int supplierId = Integer.valueOf(request.getParameter("supplier"));
			int amount = Integer.valueOf(request.getParameter("amount"));
			String cellname = request.getParameter("cell");
			Cell cell = new CellServiceImpl().get("name", cellname);
			Supplier supplier = new SupplierServiceImpl().get(supplierId);
			String remark = request.getParameter("remark");
			String[] textBook = request.getParameterValues("textBook");
			if (textBook != null) {
				for (int i = 0; i < textBook.length; i++) {
					TextBook tb = new TextBookServiceImpl().get(Integer.valueOf(textBook[i]));
					stockReceive.setAdmin((Admin) request.getSession().getAttribute("admin"));
					stockReceive.setAmount(amount);
					stockReceive.setRemark(remark);
					stockReceive.setTextBook(tb);
					stockReceive.setSupplier(supplier);
					stockReceive.setDateTime(new Date());
					if (receiveServiceImpl.add(stockReceive)) {
						StockSelect ss = new StockSelect();

						tb.setCell(cell);
						tb.getStockReceives().add(stockReceive);
						new TextBookServiceImpl().update(tb);
						cell.getTextBooks().add(tb);
						
						ss.setAmount(amount);
						ss.setCell(cell);
						ss.setCreateDate(new Date());
						ss.setTextBook(tb);
						new StockServiceImpl().add(ss);
						
						try {
							cell.getStockSelect().add(ss);
							new CellServiceImpl().update(cell);
						} catch (Exception e) {
							// TODO: handle exception
							System.out.println(e.getMessage());
						}
						
						supplier.getStockReceives().add(stockReceive);
						new SupplierServiceImpl().update(supplier);

						request.getRequestDispatcher("/receiveServlet?condition=list&currentPage=0").forward(request,
								response);
					} else {
						System.out.println("error");
					}
				}
			}
		} else if ("list".equals(request.getParameter("condition"))) {
			int currentPage = 0;
			if (request.getParameter("goalpage") == null) {
				currentPage = Integer.valueOf(request.getParameter("currentPage")) - 1;
			} else
				currentPage = Integer.valueOf(request.getParameter("goalpage")) - 1;

			PageResults pageResults = receiveServiceImpl.listByPage(currentPage);

			request.setAttribute("pageResults", pageResults);
			request.setAttribute("condition", "list");
			request.setAttribute("list", null);

			request.getRequestDispatcher("/pages/storage/storage002/receive_query.jsp").forward(request, response);

		} else if ("query".equals(request.getParameter("condition"))) {
			int currentPage = 0;
			if (request.getParameter("goalpage") == null) {
				currentPage = Integer.valueOf(request.getParameter("currentPage")) - 1;
			} else
				currentPage = Integer.valueOf(request.getParameter("goalpage")) - 1;

			String supplier = null;
			String textBook = null;
			String start = null;
			String end = null;
			String list = null;

			if (request.getParameter("list") == null) {
				start = request.getParameter("start") == null ? "%" : request.getParameter("start");
				end = request.getParameter("end") == null ? "%" : request.getParameter("end");
				supplier = request.getParameter("supplier") == null ? "%" : request.getParameter("supplier");
				textBook = request.getParameter("textBook") == null ? "%" : request.getParameter("textBook");
				list = start + "," + end + "," + supplier + "," + textBook;
			} else {
				String str = new String(request.getParameter("list").getBytes("iso-8859-1"), "utf-8");
				String[] strs = str.split(",");
				for (int i = 0; i < strs.length; i++) {
					if (i == 0)
						start = i == 0 ? strs[i] : "%";
					if (i == 1)
						end = i == 1 ? strs[1] : "%";
					if (i == 2)
						supplier = i == 2 ? strs[2] : "%";
					if (i == 3)
						textBook = i == 2 ? strs[3] : "%";
				}
				list = start + "," + end + "," + supplier + "," + textBook;
			}

			PageResults pageResults = receiveServiceImpl.query(start, end, supplier, textBook, currentPage);

			request.setAttribute("pageResults", pageResults);
			request.setAttribute("condition", "query");
			request.setAttribute("list", list);

			request.getRequestDispatcher("/pages/storage/storage002/receive_query.jsp").forward(request, response);
		}

	}

}
